package com.wson.adapter.clouddisk.impl;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import com.wson.adapter.codisk.AbstractCodiskAdapter;
import com.wson.adapter.codisk.ICodiskAdapter;
import com.wson.model.adapter.oauthaccount.IOAuthAccountView;
import com.wson.model.clouddisk.account.ICodiskAccountManip;
import com.wson.model.clouddisk.account.ICodiskAccountMeta;
import com.wson.model.clouddisk.account.ICodiskAccountView;
import com.wson.model.clouddisk.file.ICodiskFileView;
import com.wson.model.clouddisk.provider.ICodiskProviderView;
import com.wson.platform.factory.impl.BeanFactory;
import com.wson.util.function.HttpUtil;

public class CodiskAdapterCoolpanImpl  extends AbstractCodiskAdapter implements ICodiskAdapter{

	//http://open.kanbox.com/introduce
	
	
	public final static String URL_AUTHORIZE = "https://auth.kanbox.com/0/auth";
	public final static String URL_ACCESSTOKEN = "https://auth.kanbox.com/0/token";
	//public final static String APP_KEY = "";
	//public final static String APP_SECRET = "";
	
	
	public CodiskAdapterCoolpanImpl(ICodiskAccountView account,
			ICodiskProviderView provider) {
		super(account, provider);
	}

	@Override
	protected String generateAuthorizationURL(String callback) throws Exception {
		
		/**
		 * response_type 必选 必须设置成“code”。 
		client_id 必选 客户端提供的客户端ID（可以通过Developer Page获取）。 
		redirect_uri 必选 当取得Authorization Code以后，将用户重新导向该URI。本地应用程序可以采用特殊字符串：urn:ietf:wg:oauth:2.0:oob。 
		user_language 可选 二位语言编码(依据 ISO 639-1)。例如：“ZH”代表中文。 
		user_platform 可选 以下字符串识别调用操作系统平台： "web", "windows", "mac", "linux", "iphone", "ipad", "android", "symbian"。 

		 */
		String authorurl = URL_AUTHORIZE+"?"
				+ HttpUtil.generateHttpParam("response_type", "code")
				+ HttpUtil.generateHttpParam("client_id", this.getOAuthProvider().getAppKey())
				+ HttpUtil.generateHttpParam("redirect_uri", HttpUtil.encodeURLParam(callback))
				+ HttpUtil.generateHttpParam("user_language", "ZH")
				+ HttpUtil.generateHttpParam("user_platform", "web")
				;
		
		
		return authorurl;
	}



	@Override
	public void movedir(String directorysrc, String directorydest)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public ICodiskFileView mkdir(String directory) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ICodiskFileView upload(String path, InputStream is, long size)
			throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ICodiskFileView uploadshare(String path, InputStream is, long size)
			throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String share(String path) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ICodiskFileView filemeta(String fileid) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}



	@Override
	public ICodiskFileView download(String fileid) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void deletefile(String fileid) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void deletedir(String dirid) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void retrieveAccess(IOAuthAccountView account,
			String access_callback_action, Map<String, Object> params)
			throws Exception {
		/**
		 * 参数 
grant_type 必选 必须设置成“authorization_code”。 
client_id 必选 客户端ID（可以通过Developer Page获取）。 
client_secret 必选 客户端密钥（可以通过Developer Page获取）。 
code 必选 之前获得的Authorization Code（获取Authorization Code）。 
redirect_uri 必选 之前提供的重定向URI（获取Authorization Code）。 

		 */
		String accessurl = URL_ACCESSTOKEN+"?"
				+ HttpUtil.generateHttpParam("grant_type", "authorization_code")
				+ HttpUtil.generateHttpParam("client_id", this.getOAuthProvider().getAppKey())
				+ HttpUtil.generateHttpParam("client_secret", this.getOAuthProvider().getAppSecret())
				+ HttpUtil.generateHttpParam("code", params.get("code"))
				+ HttpUtil.generateHttpParam("redirect_uri", this.generateRequestOAuthCallbackUrl(account, access_callback_action))
				;


		
		try {
			
			/**
			 * 响应示例 
				{ 
				"access_token": "SlAV32hkKG", 
				"token_type": "Bearer" 
				"expires_in": 3600, 
				"refresh_token": "5c32995dd5c7b3ff8e1a6b047e9f3af4" 
				} 
			 */
			

			JSONObject jb = (JSONObject)JSONValue.parse(this.doPost(accessurl)); 
			String access_token = (String)jb.get("access_token");
			//String token_type = (String)jb.get("token_type");
			//long expires_in = Long.parseLong((String)jb.get("token_type"));
			String refresh_token = (String)jb.get("refresh_token");
			
			ICodiskAccountView user = this.retrieveCurrentAccount(access_token);
			
			this.saveAssessToken(account, access_token, refresh_token, null, ""+user.getID(), user.getAccountName(), user.getShortText());
			
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {

		}
		
	}

	
	@Override
	public ICodiskFileView upload(ICodiskFileView file) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<ICodiskFileView> listfiles(String directory) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	protected  ICodiskAccountView retrieveCurrentAccount(String access_token)throws Exception{
		String url = "https://api.kanbox.com/0/info?bearer_token="+access_token;
		
		String result = this.doPost(url);
		
		if(result!=null){
			ICodiskAccountView account = (ICodiskAccountView)BeanFactory.getCurrentFactory().getModelFactory().getModel(ICodiskAccountMeta.META_ID);
			
			JSONObject jb = (JSONObject)JSONValue.parse(result); 
			((ICodiskAccountManip)account).setAccountName((String)jb.get("email"));
			((ICodiskAccountManip)account).setSpaceQuota((Long)jb.get("space_quota"));
			((ICodiskAccountManip)account).setSpaceUsed((Long)jb.get("space_used"));
			
			
			return account;
		}
		return null;
	}
	
	
	protected  String doPost(String url)throws Exception{
		PostMethod post = new PostMethod(url);
		try{
			HttpClient httpclient = new HttpClient();
			
			post.addRequestHeader("Content-Type", "application/json");
			
			int result = httpclient.executeMethod(post);
			
			if(result!=HttpStatus.SC_OK)
				return null;
			return post.getResponseBodyAsString();
		
		} catch (Exception ex) {
			throw ex;
		} finally {
			post.releaseConnection();
		}
	}

	@Override
	public void copydir(String directorysrc, String directorydest)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public String retrieveProvisionUrl(ICodiskFileView dir) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
	
	
}
